package main

import (
	"github.com/kardianos/service"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
)

type Program struct {
	stopped bool
	cmd     *exec.Cmd
}

func (p *Program) Start(s service.Service) error {
	go p.runService(s)
	return nil
}

func (p *Program) runCmd() error {
	loadConfig()

	log.Printf("=========================================【%v】=============================================\n", runConfig.AppTitle)
	log.Printf("工作目录：%v", runConfig.WorkDir)
	log.Printf("程序目录：%v", runConfig.AppDir)
	log.Printf("Java命令：%v", runConfig.JavaCommand)
	log.Printf("运行主类：%v", runConfig.MainClass)
	log.Printf("字符编码：%v", runConfig.Encoding)
	log.Printf("临时目录：%v", runConfig.TmpDir)
	log.Printf("内存配置：最小%v 最大%v", runConfig.MinMem, runConfig.MaxMem)
	log.Printf("环境变量：%v", strings.Join(runConfig.Env, ":"))

	cmdLine := generateCommand(runConfig)
	name, args := SplitCommand(cmdLine)
	cmd := exec.Command(name, args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = runConfig.WorkDir
	cmd.Env = append(os.Environ(), runConfig.Env...)
	log.Printf("执行命令 > %v", cmdLine)
	p.cmd = cmd
	return cmd.Run()
}

func (p *Program) runService(s service.Service) {
	defer func() {
		if service.Interactive() {
			_ = p.Stop(s)
		} else {
			_ = s.Stop()
		}
	}()

	if runConfig.AutoStartWhenExist {
		for p.stopped != true {
			err := p.runCmd()
			if err != nil {
				log.Printf("运行异常[%v], %v", runConfig.AppTitle, err.Error())
			}
			log.Printf("即将重启[%v]", runConfig.AppTitle)
			time.Sleep(time.Duration(runConfig.AutoStartDelay) * time.Second)
		}
	} else {
		err := p.runCmd()
		if err != nil {
			log.Printf("运行异常[%v], %v", runConfig.AppTitle, err.Error())
		}
	}
}

func (p *Program) Stop(s service.Service) error {
	log.Printf("停止服务[%v]", runConfig.AppTitle)
	p.stopped = true

	if p.cmd != nil {
		_ = p.cmd.Process.Kill()
	}

	if service.Interactive() {
		os.Exit(0)
	}
	return nil
}
